package com.example.myapplication.ui.list;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.myapplication.BR;
import com.example.myapplication.R;
import com.example.myapplication.activity.ListActivity;
import com.example.myapplication.activity.MainActivity;
import com.example.myapplication.activity.MainViewModel;
import com.example.myapplication.common.CommonRecyclerAdapter;
import com.example.myapplication.databinding.FragmentHomeBinding;
import com.example.myapplication.databinding.FragmentListBinding;
import com.example.myapplication.repository.data.File;
import com.example.myapplication.repository.network.FileService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ListFragment extends Fragment{
    FragmentListBinding binding;

//    ListViewModel listViewModel;
    List<File> fileList;

    MainViewModel mainViewModel;

    CommonRecyclerAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        binding = FragmentListBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
//        listViewModel = new ViewModelProvider(this).get(ListViewModel.class);
        fileList = new ArrayList<>();
        //获取宿主activity中数据
        mainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);

        adapter = new CommonRecyclerAdapter(this,getContext(), R.layout.list_item, BR.file, fileList, true) {
            @Override
            public void click(ViewHolder holder, int position, View view) {
                File file = fileList.get(position);
                Log.i("size",fileList.size()+"");
                if(file.getIsDir() == 0){
                    Toast.makeText(getContext(),fileList.get(position).getFileName(),Toast.LENGTH_SHORT).show();
                }else{
//                    Bundle bundleSimple = new Bundle();
//                    bundleSimple.putString("dir", "/".equals(dir)?dir+file.getFileName():dir+"/"+file.getFileName());
                    String dir = mainViewModel.getDir().getValue();
                    mainViewModel.getDir().postValue("/".equals(dir)?dir+file.getFileName():dir+"/"+file.getFileName());
//                    getActivity().getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().beginTransaction().replace(R.id.nav_host_fragment_activity_main,ListFragment.class,savedInstanceState)
//                            .addToBackStack(null).commit();
//                    fileList = new ArrayList<>();
                    list("/".equals(dir)?dir+file.getFileName():dir+"/"+file.getFileName());
                }
            }
        };

        binding.listView.setAdapter(adapter);
//        Bundle bunde = this.getIntent().getExtras();
//        dir = bunde != null?bunde.getString("dir"):"/";
//        dir = savedInstanceState != null ? savedInstanceState.getString("dir"):"/";
        Log.i("dir",mainViewModel.getDir().getValue());

        list(mainViewModel.getDir().getValue());
        return root;
    }

    private void list(String dir){
        //创建 OkHttp 实例，添加日志拦截器，以便调试
        OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
//        创建 Retrofit 实例，配置 baseUrl, 添加 ConverterFactory。
        Retrofit retrofit = new Retrofit.Builder().
                baseUrl("https://pan.baidu.com")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        //创建 Service 实例
        FileService fileService = retrofit.create(FileService.class);
        //创建 Call 实例
        fileService.list("list", "121.a0525002951f1ddc87ab02361d76c41a.YlHrbdiR_4GFf4IsHuXY8QEresPwldU31d-LT2w.8iYEHg", dir).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject res = response.body();
                Log.i("object:", res.toString());
                if (res.get("errno").getAsInt() == 0) {
                    JsonArray array = res.getAsJsonArray("list");
                    fileList = new ArrayList<>();
                    for (JsonElement temp : array) {
                        JsonObject tempAsJsonObject = temp.getAsJsonObject();
                        File file = new File();
                        file.setFileName(tempAsJsonObject.get("server_filename").getAsString());
                        file.setSize(tempAsJsonObject.get("size").getAsInt());
                        file.setIsDir(tempAsJsonObject.get("isdir").getAsInt());
                        file.setCategory(tempAsJsonObject.get("category").getAsInt());
                        fileList.add(file);
                    }
//                    adapter.notifyDataSetChanged();
                    adapter.setList(fileList);
                } else {
                    Toast.makeText(getContext(), "请求失败，请检查网络", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.e("訪問失敗", "訪問失敗");
            }
        });
    }
}
